/*
*  功能：用户状态
*
*/

import Cookies from 'js-cookie'
import * as api from '@/api'

const SET_TOKEN = "SET_TOKEN"
const REMOVE_TOKEN = "REMOVE_TOKEN"
const SET_NAME = "SET_NAME"
const SET_ROLES = "SET_ROLES"
const SET_AVATAR = "SET_AVATAR"

//定义state
const state = {
  token: Cookies.get(SET_TOKEN),  //身份令牌
  name: '',   //用户名
  roles: [],  //角色
  avatar: ''  //图标
}

//定义getters -- 相当于Store的计算属性
const getters = {
  token: function (state, getters) {
    return state.token
  },
  name: function (state, getters) {
    return state.name
  },
  roles: function (state, getters) {
    return state.roles
  },
  avatar: function (state, getters) {
    return state.avatar
  },
  loggedIn: function (state, getters) {
    return state.token !== ''
  }
}

//Mutations
//作用：同步调用 store.commit 方法，更改 Vuex 的 store 中的状态的唯一方法
const mutations = {
  [SET_TOKEN]: function (state, token) {
    state.token = token
    Cookies.set(SET_TOKEN, token, { expires: 7 })
  },
  [SET_NAME]: function (state, name) {
    state.name = name
  },
  [SET_ROLES]: function (state, roles) {
    state.roles = roles
  },
  [SET_AVATAR]: function (state, avatar) {
    state.avatar = avatar
  }
}

//Actions
//作用：1.提交的是 mutation，而不是直接变更状态
//     2.可以包含任意异步操作
const actions = {
  //userinfo: {username: '', password: ''}
  login: function ({commit}, username, password) {
    return new Promise((resolve, reject)=>{
      api.login(username, password)
        .then(function ({token}) {
          //保存令牌
          console.log(`setToken: ${token}`);
          commit(SET_TOKEN, token)
          resolve()
        })
        .catch(error=>{
          console.log(`store.user.login()>${error}`)
          reject(error)
        })      //通知调用者，有错误发生
    })

  },
  logout: function ({commit}) {
    return new Promise((resolve, reject)=>{
      api.logout()
        .then(function () {
          //清理令牌和用户信息
          commit(SET_TOKEN, '')
          Cookies.remove(SET_TOKEN)
          commit(SET_NAME, '')
          commit(SET_ROLES, [])
          commit(SET_AVATAR, '')
          //通知调用者调用完成
          resolve()
        })
        .catch(error=>{
          console.log(`store.user.logout()>${error}`)
          //清理令牌和用户信息
          commit(SET_TOKEN, '')
          Cookies.remove(SET_TOKEN)
          commit(SET_NAME, '')
          commit(SET_ROLES, [])
          commit(SET_AVATAR, '')

          reject(error)//通知调用者有错误发生

        })
    })
  },
  getUserInfo: function ({commit}) {
    return new Promise((resolve, reject)=>{
      api.getUserInfo()
        .then(function (data) {
          //保存用户信息
          commit(SET_NAME, data.name)
          commit(SET_ROLES, data.roles)
          commit(SET_AVATAR, data.avatar)

          //
          resolve(data)
        })
        .catch(function (error) {
          console.log(`store.user.getUserInfo()>${error}`)
          reject(error)
        })
    })
  },
  getTableList: function ({commit}) {
    return new Promise((resolve, reject)=>{
      api.getTableList()
        .then(data=>{
          resolve(data)
        })
        .catch(error=>{
          console.log(`store.user.getTableList()>${error}`)
          reject(error)
        })
    })
  },
  changeRole: function ({getters,commit,dispatch}, role) {
    if(role === getters.token){
      return Promise.resolve()
    } else {
      return new Promise((resolve, reject) => {
          commit(SET_TOKEN, role)
          dispatch('getUserInfo')
            .then(()=>resolve())
            .catch(error=>{
              console.log(`store.user.changeRole>${error}`)
              reject(error)
            })
      })
    }
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
